<?php
namespace Admin\Controller;
use Common\Util\Filedir;
use Think\Controller;

class AdminController extends Controller{
	public $c_admin_info = null;
	protected $base_url;
	protected $admin_url;
	 /**
     * 后台控制器初始化
     */
	protected function _initialize(){
		header('Content-Type:text/html;charset=utf-8');
		// 检查IP地址访问
	    if(!in_array(get_client_ip(),explode(',',C('ADMIN_ALLOW_IP')))){
	         //$this->error('403:禁止访问');
	    }
	    $this->base_url = '/';
	    $this->admin_url = '/Manage.php';
	    $this->assign('base_url',$this->base_url);
	    $this->assign('admin_url',$this->admin_url);

        $this->assign('this_url_action',__ACTION__);
		/*验证登陆*/
		define('ADMIN_UID', is_login());
		if(!ADMIN_UID){//未登陆 跳转到登陆页面
			$this->redirect('Public/login');
		}

		/*获取登陆用户信息*/
		$admin = D('admin');
		if($admin_info = $admin->getUserInfo(ADMIN_UID)){
			$this->c_admin_info = $admin_info;
			$this->assign('admin_info',$admin_info);
			//读取用户所属角色
			if($admin_info['id'] == 1){
				$this->admin_role_name = '超级管理员';
			}else{
				if(!$groupinfo = D("AuthGroupAccess")->where("uid=$admin_info[id]")->find()){
					$this->admin_role_name = '无操作权限';
				}else{
					$authgroup = D("AuthGroup")->where("id=$groupinfo[group_id]")->find();
					$this->admin_role_name = $authgroup['title']?$authgroup['title']:'无操作权限';
				}
			}
		}else{
			session('user_auth', null);
        	session('user_auth_sign', null);
        	$this->redirect('Public/login');
		}
		if($admin_info['user_status'] == 0){
			session('user_auth', null);
        	session('user_auth_sign', null);
        	$this->redirect('Public/login');
		}
		//是否是超级管理员
        define('IS_ROOT',   is_administrator());
//
//		/*进行权限验证*/
//        if(!IS_ROOT){
//        	//读取菜单
//        	$this->admin_menu	= D('menu')->getMenuList($where="hide=0 and ");
//        	$access =   $this->accessControl();
//            if ( false === $access ) {
//                $this->error('403:禁止访问');
//            }elseif(null === $access ){
//                //检测访问权限
//                $rule  = strtolower(CONTROLLER_NAME.'/'.ACTION_NAME);
//                if ( !$this->checkRule($rule,1)){
//                    $this->error('未授权访问!');
//                }else{
//                    // 检测分类及内容有关的各项动态权限
//                    $dynamic    =   $this->checkDynamic();
//                    if( false === $dynamic ){
//                        $this->error('未授权访问!');
//                    }
//                }
//            }
//        }else{
        	//读取菜单
        	$this->admin_menu	= D('menu')->getMenuList($where="hide=0 and ");
//        }
	}
	/**
     * 权限检测
     * @param string  $rule    检测的规则
     * @param string  $mode    check模式
     * @return boolean
     */
    final protected function checkRule($rule, $type=1, $mode='url'){
        static $Auth    =   null;
        if (!$Auth) {
            $Auth       =   new \Think\Auth();
        }
        if(!$Auth->check($rule,ADMIN_UID,1,$mode)){
            return false;
        }
        return true;
    }

	/**
     * action访问控制,在 **登陆成功** 后执行的第一项权限检测任务
     *
     * @return boolean|null  返回值必须使用 `===` 进行判断
     *
     *   返回 **false**, 不允许任何人访问(超管除外)
     *   返回 **true**, 允许任何管理员访问,无需执行节点权限检测
     *   返回 **null**, 需要继续执行节点权限检测决定是否允许访问
     */
    final protected function accessControl(){
        $allow = [
            'Index/index',
            'Index/welcome'
        ];
        $deny  = C('DENY_VISIT');
        $check = strtolower(CONTROLLER_NAME.'/'.ACTION_NAME);
        if ( !empty($deny)  && in_array_case($check,$deny) ) {
            return false;//非超管禁止访问deny中的方法
        }
        if ( !empty($allow) && in_array_case($check,$allow) ) {
            return true;
        }
        return null;//需要检测节点权限
    }

    /**
     * 检测是否是需要动态判断的权限
     * @return boolean|null
     *      返回true则表示当前访问有权限
     *      返回false则表示当前访问无权限
     *      返回null，则表示权限不明
     *
     */
    protected function checkDynamic(){}


	protected function lists ($model,$where=array(),$order='',$field=true,$p=10){
		$Model = M($model);
		$count      = $Model->where($where)->count();
		if($p > 0){
			$p = $p;
		}else{
			$p = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
		}
		$Page       = new \Think\Page($count,$p);
		if($count>$p){
            $Page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
		$Page->parameter=I('get.');
		$this->page_show      = $Page->show();// 分页显示输出
		$list = $Model->where($where)->field($field)->order($order)->limit($Page->firstRow.','.$Page->listRows)->select();
        $this->assign('list', $list);
        $this->getting	= I('get.');
		return $list;
    }

    /*=======================用户管理========================*/
    public function index(){
    	$admin = M('Admin');
    	if(isset($_GET['name'])){
            $map['user_login']    =   array('like', '%'.(string)I('get.name').'%');
        }
    	$list = $admin->where($map)->order("id Asc")->select();

    	$this->assign('list', $list);
    	$this->meta_title = '管理员管理';
    	$this->display();
    }
    public function add(){
    	if(IS_AJAX){
    		$admin = D('Admin');
            $data = $admin->create();
            if($data){
                if($insert_id = $admin->add()){
                    $msg_data['status']	= 1;
	    			$msg_data['msg']	= '新增成功';
	    			$this->ajaxReturn($msg_data);
                } else {
                    $msg_data['status']	= 0;
	    			$msg_data['msg']	= '新增失败';
	    			$this->ajaxReturn($msg_data);
                }
            } else {
                $msg_data['status']	= 0;
	    		$msg_data['msg']	= $admin->getError();
	    		$this->ajaxReturn($msg_data);
            }
    	}
    	$this->meta_title = '用户添加';
    	$this->display();
    }

    public function edit($id=0){
    	if(IS_AJAX){
    		$user_pass = I('post.user_pass');
    		$data['user_email']	= I('post.user_email');
    		$data['mobile']	= I('post.mobile');
    		$data['id']	= I('post.id');
			$data['u_province'] = $_POST['u_province']?$_POST['u_province']:'';
			$data['u_city'] = $_POST['u_city']?$_POST['u_city']:'';
			$data['u_district'] = $_POST['u_district']?$_POST['u_district']:'';
    		if(!empty($user_pass)){
    			if(I('post.user_pass') == I('post.m_user_pass')){
    				$data['user_pass']	= pass_md5(I('post.user_pass'));
    			}else{
    				$msg_data['status']	= 0;
	    			$msg_data['msg']	= '两次密码输入不一致';
	    			$this->ajaxReturn($msg_data);
    			}
    		}
    		$admin = M('Admin');
            if($admin->save($data)){
                $msg_data['status']	= 1;
	    		$msg_data['msg']	= '修改成功';
	    		$this->ajaxReturn($msg_data);
            } else {
                $msg_data['status']	= 0;
	    	 	$msg_data['msg']	= '修改失败';
	    		$this->ajaxReturn($msg_data);
            }
    	}
    	$info = array();
        /* 获取数据 */
        $info = M('Admin')->field(true)->find($id);
        if(false === $info){
            $this->error('获取配置信息错误');
        }
        $this->assign('info', $info);
    	$this->meta_title = '用户编辑';
    	$this->display();
    }
    //用户授权
    public function setAuth(){
    	if(IS_AJAX){
    		$id 		= I("post.id");
    		$group_id	= I("post.group_id");
    		if(M("AuthGroupAccess")->where("uid=$id")->find()){
    			if(M("AuthGroupAccess")->where("uid=$id")->save(array('group_id'=>$group_id))){
    				$msg_data['status']	= 1;
	    			$msg_data['msg']	= '操作成功';
	    			$this->ajaxReturn($msg_data);
    			}else{
    				$msg_data['status']	= 0;
	    			$msg_data['msg']	= '操作失败1';
	    			$this->ajaxReturn($msg_data);
    			}
    		}else{
    			if(M("AuthGroupAccess")->add(array('uid'=>$id,'group_id'=>$group_id))){
    				$msg_data['status']	= 1;
	    			$msg_data['msg']	= '操作成功';
	    			$this->ajaxReturn($msg_data);
    			}else{
    				$msg_data['status']	= 0;
	    			$msg_data['msg']	= '操作失败2';
	    			$this->ajaxReturn($msg_data);
    			}
    		}
    	}
    	$id = I('get.id');
    	if($id == C('USER_ADMINISTRATOR')){
    		$this->error('不允许对超级管理员执行该操作');
    	}
    	$auth_group_access = M('AuthGroupAccess')->where("uid=$id")->find();
    	if($auth_group_access){
    		$this->auth_group_access	= $auth_group_access;
    	}else{
    		$this->auth_group_access	= '';
    	}
    	//读取所有权限列表
    	$this->auth_group = M('AuthGroup')->where("status=1")->select();
    	$this->display();
    }

    //更新状态
    public function changeStatus(){
    	$id = I('get.id');
    	if($id == C('USER_ADMINISTRATOR')){
    		$this->error('不允许对超级管理员执行该操作');
    	}
    	$method = I('get.method');
    	$map['id'] =   $id;
    	switch (strtolower($method)){
    		case 'forbiduser'://禁用
    			$data    =  array('user_status' => 0);
    			if(M('Admin')->where($map)->save($data)!==false){
    				$this->success('操作成功');
    			}else{
    				$this->error('操作失败');
    			}
                break;
            case 'resumeuser'://启用
    			$data    =  array('user_status' => 1);
    			if(M('Admin')->where($map)->save($data)!==false){
    				$this->success('操作成功');
    			}else{
    				$this->error('操作失败');
    			}
                break;
            case 'deleteuser'://删除
            	if(M('Admin')->where($map)->delete()!==false){
            		$this->success('操作成功');
            	}else{
            		$this->error('操作失败');
            	}
                break;
            default:
                $this->error('参数非法');
    	}
    }

	public function clear_cache(){
		clear_cache();
		$this->success ('清理缓存成功',U('Index/welcome'));
	}
	//清理海报缓存
	public function clear_user_haibao(){
        $file_do = new Filedir();
        $file_do->delete_dir_file(SITE_PATH.'Data/tempImage');
        $file_do->delete_dir_file(SITE_PATH.'Data/userRcode');
        $this->success ('清理海报缓存成功',U('Index/welcome'));
    }

	//日志管理
	public function action_log(){
		//获取列表数据
		$map = [];
		$list   =   $this->lists('action_log', $map,"id desc",true,20);
		$this->assign('_list', $list);
		$this->meta_title = '系统日志';
		$this->display();
	}

	public function getRegionList(){
		$region = M("Region");
		$data = $_GET['data']?trim($_GET['data']):0;
		if($data == 0){
			$re_list = $region->where("PARENT_ID=1")->order("REGION_ID Asc")->cache('one_region',3600*24*30)->select();
			$return_data['message'] = '';
			$return_data['status'] = true;
			$return_data['statusCode'] = 'R5';
			$return_data['result'] = $re_list;
			echo json_encode($return_data);exit();
		}else{
			$re_info = $region->where("REGION_ID=$data")->find();
			if($re_info){
				$c_str = 'one_'.$data;
				$re_list = $region->where("PARENT_ID=$re_info[region_id]")->order("REGION_ID Asc")->cache($c_str,3600*24*30)->select();
				$return_data['message'] = '';
				$return_data['status'] = true;
				$return_data['statusCode'] = 'R5';
				$return_data['result'] = $re_list;
				echo json_encode($return_data);exit();
			}else{
				$return_data['message'] = '';
				$return_data['status'] = false;
				$return_data['statusCode'] = 'R5';
				$return_data['result'] = '';
				echo json_encode($return_data);exit();
			}
		}
	}

    public function return_json_data($status,$msg){
        $return_data['status'] = $status;
        $return_data['msg'] = $msg;
        echo json_encode($return_data);exit();
    }

    public function return_json_data_code($code,$info){
        $return_data['code'] = $code;
        $return_data['info'] = $info;
        echo json_encode($return_data);exit();
    }

    /**
     * 返回封装后的 API 数据到客户端
     * @param int $code
     * @param string $msg
     * @param array $data
     * @return array
     */
    protected function renderJson($code = 0, $msg = '', $data = [])
    {
        return json_encode(array('code' => $code,'data'=>$data,'msg'=>$msg,'url'=>''));
    }
    /**
     * 返回操作成功json
     * @param array $data
     * @param string|array $msg
     * @return array
     */
    protected function renderSuccess($data = [], $msg = 'success')
    {
        echo $this->renderJson(1, $msg, $data);exit();
    }
    /**
     * 返回操作失败json
     * @param string $msg
     * @param array $data
     * @return array
     */
    protected function renderError($msg = 'error', $data = [])
    {
        echo $this->renderJson(0, $msg, $data);exit();
    }
    /**
     * 返回操作失败 且返回上一级
     * @param string $msg
     * @param array $data
     * @return array
     */
    protected function renderBackError($msg = 'error', $data = [])
    {
        echo $this->renderJson(201, $msg, $data);exit();
    }
    /**
     * 未登陆返回json
     * @param string $msg
     * @param array $data
     * @return array
     */
    protected function renderNoLogin($msg = 'error', $data = []){
        echo $this->renderJson(101, $msg, $data);exit();
    }

    /**
     * 未授权返回json
     * @param string $msg
     * @param array $data
     */
    protected function renderNoAuth($msg = 'error', $data = []){
        echo $this->renderJson(102, $msg, $data);exit();
    }

}
?>
